document.body.style.overflow='hidden';
let resources = ['../imgs/loading.gif','../imgs/yinzh.png','../audio/3.mp3','../audio/click.mp3','../audio/slide.mp3'];
for (let index = 1; index <= 18; index++) {
  resources.push('../imgs/' + index + '.png');
}
for (let index = 1; index <= 12; index++) {
  resources.push('../imgs/result-' + index + '.png');
}
for (let index = 1; index <= 6; index++) {
  resources.push('../imgs/poster-' + index + '.png');
}
var loader = new resLoader({
  resources: resources,
  onStart: function (total) {
  },
  onProgress: function (current, total) {
    var percent = parseInt(current / total * 100);
    $('#progress').text(percent + '%');
  },
  onComplete: function (total) {
    $('#load-page').css('display', 'none');
    $('#home-page').css('display', 'block');
    setTimeout(function(){
      $('#png-12').attr('class','animated pulse infinite')
    }, 4500)
  }
});




$('#png-12').click(function () { // 点击挑战
  $('#home-page').css('display', 'none');
  $('#game-rule-1').css('display', 'block');
  $('#png-10').css('display','block')
  $('#png-17').css('display','none')
  audio.play();
})
$('#start-btn-1').click(function () { // start第一关游戏
  $('#game-rule-1').css('display', 'none');
  $('#game-page-1').css('display', 'block');
  startGame1();
})
$('#start-btn-2').click(function () { // start第二关游戏
  $('#game-rule-2').css('display', 'none');
  $('#game-page-2').css('display', 'block');
  startGame2();
})

let ticker1;
let ticker2;
let time1 = 25;
let time2 = 25;

function startTick1() {
  ticker1 = setInterval(function () {
    let i = --time1;
    $('#time-1').text(i < 10 ? '0' + i : i);
    if (time1 === 0) {
      endTick1();
    }
    if (time1 === 15) {
      $('#rule-1').css('display','none');
      $('#olock-1').css('display','block');
    }
    if (time1 === 5) {
      $('#olock-1').addClass('animated flash infinite');
    }
  }, 1000)
}

function endTick1() {
  clearInterval(ticker1);
  time1 = 25;
  console.log('第一关答对', correctGame1, '进行了多少步', gameStep);
  $('#game-page-1').css('display', 'none');
  $('#time-up-page').css('display', 'block');
  setTimeout(function () {
    $('#game-rule-2').css('display', 'block');
    $('#time-up-page').css('display', 'none');
  }, 2000);
}

function startTick2() {
  ticker2 = setInterval(function () {
    let i = --time2;
    $('#time-2').text(i < 10 ? '0' + i : i);
    if (time2 === 0) {
      endTick2();
    }
    if (time2 === 15) {
      $('#rule-2').css('display','none');
      $('#olock-2').css('display','block');
    }
    if (time2 === 5) {
      $('#olock-2').addClass('animated flash infinite');
    }
  }, 1000)
}

function endTick2() {
  clearInterval(ticker2);
  time2 = 25;
  console.log('第二关答对', correctGame2, '进行了多少步', gameStep2);
  $('#game-page-2').css('display', 'none');
  $('#time-up-page').css('display', 'block');
  setTimeout(function () {
    $('#time-up-page').css('display', 'none');
    $('.last-page').css('display', 'block');
    showScore();
  }, 2000);
}

function getRandowm() {
  let i = Math.random() * 10;
  return i >= 5 ? 1 : 0;
}
const upArrow = '<div class="animated fadeIn jt-item jt-item-up">' +
  '<img class="jt png-7" src="./imgs/7.png" alt="向上箭头">' +
  '<img class="png-6" src="./imgs/6.png" alt="龙小湖">' +
  '</div>';
const downArrow = '<div class="animated fadeIn jt-item jt-item-down">' +
  '<img class="jt png-8" src="./imgs/8.png" alt="向上箭头">' +
  '<img class="png-6" src="./imgs/6.png" alt="龙小湖">' +
  '</div>';
let bg = {
  red: {
    color: 'red',
    bg: 'rgb(237, 124, 126)',
    text: '红'
  },
  blue: {
    color: 'blue',
    bg: 'rgb(154, 214, 239)',
    text: '蓝'
  },
  white: {
    color: 'white',
    bg: '#fff',
    text: '白'
  },
  green: {
    color: 'green',
    bg: 'rgb(21,163,163)',
    text: '绿'
  },
  black: {
    color: 'black',
    bg: '#333333',
    text: '黑'
  }
}
const arrows = [upArrow, downArrow];
let arrowOptions = [{
    color: bg.red.color,
    arrow: upArrow
  }, //  0  红上
  {
    color: bg.blue.color,
    arrow: upArrow
  }, // 1  蓝上
  {
    color: bg.red.color,
    arrow: downArrow
  }, // 2 红下
  {
    color: bg.blue.color,
    arrow: downArrow
  } // 3 蓝下
];
let randomArrowOptions = [];
for (let index = 0; index < 200; index++) {
  randomArrowOptions.push(getRandowm());
}
let gameStep = 0;

function startGame1() {
  $('.game-1 .top').css('background', bg.red.bg);
  $('.game-1 .bottom').css('background', bg.blue.bg);
  $('#game-1-current').html(arrows[randomArrowOptions[0]])
  startTick1();
}

function toggleGame1Current() {

  $('.game-1 .top').css('background', gameStep % 2 == 0 ? bg.blue.bg : bg.red.bg);
  $('.game-1 .bottom').css('background', gameStep % 2 == 1 ? bg.blue.bg : bg.red.bg);
  $('#game-1-current').html(arrows[randomArrowOptions[gameStep + 1]])
  gameStep++;
}

var startx, starty;

//获得角度
function getAngle(angx, angy) {
  return Math.atan2(angy, angx) * 180 / Math.PI;
};

//根据起点终点返回方向 1向上 2向下 3向左 4向右 0未滑动
function getDirection(startx, starty, endx, endy) {
  var angx = endx - startx;
  var angy = endy - starty;
  var result = 0;

  //如果滑动距离太短
  if (Math.abs(angx) < 2 && Math.abs(angy) < 2) {
    return result;
  }

  var angle = getAngle(angx, angy);
  if (angle >= -135 && angle <= -45) {
    result = 1;
  } else if (angle > 45 && angle < 135) {
    result = 2;
  } else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
    result = 3;
  } else if (angle >= -45 && angle <= 45) {
    result = 4;
  }

  return result;
}
//手指接触屏幕
document.getElementById("game-page-1").addEventListener("touchstart", function (e) {
  e.preventDefault();
  startx = e.touches[0].pageX;
  starty = e.touches[0].pageY;
}, false);
document.getElementById("game-page-1").addEventListener("touchmove", function (e) {
  e.preventDefault();
  let x = e.touches[0].pageX;
  let y = e.touches[0].pageY;
  let cha = parseFloat((y -starty)/100);
  $('#game-1-current .jt-item').css('margin-top',0.6+cha+'rem');
}, false);
//手指离开屏幕
document.getElementById("game-page-1").addEventListener("touchend", function (e) {
  e.preventDefault();
  audioSlide.play();
  var endx, endy;
  endx = e.changedTouches[0].pageX;
  endy = e.changedTouches[0].pageY;
  var direction = getDirection(startx, starty, endx, endy);
  switch (direction) {
    case 1:
      judgeArrow(0); // 向上
      break;
    case 2:
      judgeArrow(1); // 向下
      break;
    default:break;
  }
}, false);
let correctGame1 = 0;

function judgeArrow(a) { // a：0 向上滑 ， a:1 向下滑
  if(a===0) {
    $('#game-1-current .jt-item').addClass('animated fadeOutUp');
  } else {
    $('#game-1-current .jt-item').addClass('animated fadeOutDown');
  }
  setTimeout(function(){
    toggleGame1Current();
  },200)
  let c = gameStep % 2; // c0 红色 c1蓝色
  if (a !== randomArrowOptions[gameStep] && c === 0) { // 红色 反方向
    correctGame1 = correctGame1 + 2;
    console.log('答对了+2分',correctGame1);
  }
  if (a === randomArrowOptions[gameStep] && c === 1) { // 蓝色 正方向
    correctGame1 = correctGame1 + 2;
    console.log('答对了+2分',correctGame1);
  }
}

const colors = ['red', 'blue', 'white','green', 'purple', 'black', 'yellow'];
const colorsCn = ['红',  '蓝', '白', '绿', '紫', '黑', '黄'];

// 红 蓝 白 绿
let randomColorOptions = {
  round1: [], // 4轮双色版  { 颜色 字 }
  round2: [], // 4轮三色版
  round3: [] // 30轮四色版
}
// 生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * minNum + 1, 10);
    case 2:
      return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
    default:
      return 0;
  }
}
// 生成从minNum到maxNum的随机数,但不含已有的数组
function getRandomNoRepeat(minNum, maxNum, had) {
  let i = randomNum(minNum, maxNum);
  if(had.indexOf(i)===-1) {
    return i;
  }
  return getRandomNoRepeat(minNum, maxNum, had);
}
function getRandomColor(i) {
  let a = getRandomNoRepeat(0,6,i);
  return colorsCn[a];
}

for (let i = 0; i < 4; i++) {
  let i1 = randomNum(0,2);
  let i2 = getRandomNoRepeat(0,2,[i1]);
  let obj1 = createObj(bg[colors[i1]].color,getRandomColor([i1]),false);
  let obj2 = createObj(bg[colors[i2]].color,getRandomColor([i2]),false);
  let arr = [obj1,obj2]
  let same = getRandowm();
  arr[same].same = true;
  let iarr = [i1,i2];
  arr[same].text = colorsCn[iarr[same]];
  randomColorOptions.round1.push(arr)
}
for (let i = 0; i < 4; i++) {
  let i1 = randomNum(0,3);
  let i2 = getRandomNoRepeat(0,3,[i1]);
  let i3 = getRandomNoRepeat(0,3,[i1,i2]);
  let obj1 = createObj(bg[colors[i1]].color,getRandomColor([i1,i2]),false);
  let obj2 = createObj(bg[colors[i2]].color,getRandomColor([i2,i3]),false);
  let obj3 = createObj(bg[colors[i3]].color,getRandomColor([i1,i3]),false);
  let arr = [obj1,obj2,obj3]
  let same = randomNum(0,2);
  arr[same].same = true;
  let iarr = [i1,i2,i3];
  arr[same].text = colorsCn[iarr[same]];
  randomColorOptions.round2.push(arr)
}
for(let i=0; i< 100; i++) {
  let arr = [0,1,2,3];
  arr.sort(function() {
    return (0.5-Math.random());
  });
  let obj1 = createObj(bg[colors[arr[0]]].color,getRandomColor([arr[0]]),false);
  let obj2 = createObj(bg[colors[arr[1]]].color,getRandomColor([arr[1]]),false);
  let obj3 = createObj(bg[colors[arr[2]]].color,getRandomColor([arr[2]]),false);
  let obj4 = createObj(bg[colors[arr[3]]].color,getRandomColor([arr[3]]),false);
  let same = randomNum(0,3);
  let arrObj = [obj1,obj2,obj3,obj4];
  arrObj[same].text = colorsCn[arr[same]];
  arrObj[same].same = true;
  randomColorOptions.round3.push(arrObj);
}
function createObj(color,text,same) {
  return {
    color: color,
    text: text,
    same: same
  }
}
let game2Arr = [
  ...randomColorOptions.round1,
  ...randomColorOptions.round2,
  ...randomColorOptions.round3
];

function startGame2() {
  startTick2();
  changeNext();
}
let correctGame2 = 0;
let gameStep2 = 0;
$(document).find(".page").on('click', '.longfor-color', function(){
  let a = $(this).attr('data-same');
  if (gameStep2%2===0) {
    audioClick1.play();
  } else {
    audioClick.play();
  }
  if(a=='true') {
    correctGame2 = correctGame2 + 2;
    console.log('答对了+2分',correctGame2);
  }
  changeNext();
})
function changeNext() {
  gameStep2++;
  if(gameStep2>=108) {
    gameStep2 = 0;
  }
  let html = '';
  for (let i = 0; i < game2Arr[gameStep2].length; i++) {
    html += '<div class="longfor-color '+ game2Arr[gameStep2][i].color +'" data-same="'+
              game2Arr[gameStep2][i].same +'">'+
              '<img class="png-5" src="./imgs/5.png" alt="龙小湖">'+
              '<span class="color">'+game2Arr[gameStep2][i].text+'</span>'+
            '</div>';
  }
  $('#longfor-current').html(html);
}
function showScore() {
  let i = getSlogan();
  $('#res-title').attr('src','./imgs/result-'+i+'.png');
  $('#res-title').attr('data-id',i);
  let s = parseInt(correctGame1 + correctGame2);
  if(s>100) { s=100; }
  $('#res-score').text(s);
  $('#res-img').attr('src','./imgs/poster-'+randomNum(1,6)+'.png');
  getCanvas();
}
function getSlogan() {
  let total = correctGame1 + correctGame2;
  if(total<=45) {
    return 1;
  }
  else if(total>45 && total<=50) {
    return 2;
  }
  else if(total>50 && total<=55) {
    return 3;
  }
  else if(total>55 && total<=60) {
    return 4;
  }
  else if(total>60 && total<=65) {
    $('#res-title').css('width','70%');
    return 5;
  }
  else if(total>65 && total<=70) {
    return 6;
  }
  else if(total>70 && total<=75) {
    return 7;
  }
  else if(total>75 && total<=80) {
    return 8;
  }
  else if(total>80 && total<=85) {
    return 9;
  }
  else if(total>85 && total<=90) {
    return 10;
  }
  else if(total>90 && total<=95) {
    return 11;
  }
  else if(total>95) {
    return 12;
  }
}

let audio = new Audio('../audio/3.mp3');
let audioClick = new Audio('../audio/click.mp3');
let audioClick1 = new Audio('../audio/click.mp3');
let audioSlide = new Audio('../audio/slide.mp3');
audio.volume = 0.3;
$('#png-17').click(function() {
  $('#png-10').css('display','block')
  $('#png-17').css('display','none')
  audio.play();
})
$('#png-10').click(function() {
  $('#png-17').css('display','block')
  $('#png-10').css('display','none')
  audio.pause();
})
$('#again-btn').click(function() {
  location.reload();
});

loader.start();

function getCanvas() {
  let mycanvas = $('#share-page')[0];
  var width = $('#share-page')[0].offsetWidth;//dom宽
  var height = $('#share-page')[0].offsetHeight;//dom高
  var scale = 2;//放大倍数
  html2canvas(mycanvas,{
    dpi: window.devicePixelRatio*2,
    scale:scale,
    width:width,
    heigth:height,
    backgroundColor: '#ffde2d',
    useCORS: true
  }).then(function(canvas) {
    canvas.id = 'resultCanvas';
    let dataurl = canvas.toDataURL("image/png");
    imgSrc = dataurl;
    $("#canvas").html("<img src='"+dataurl+"'/>");
    $("#share-page").css('display','none');
    $('#canvas').css('visibility','visible');
  });
}
